package org.dragonnova.lamp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import org.dragonnova.lamp.utils.WifiUtil;

/**
 * Created by hucn on 2016/8/19.
 * 获取当前手机状况的类
 */
public class PhoneInfo {

    private static final String TAG = PhoneInfo.class.getSimpleName();

    private static PhoneInfo instance;

    private WifiManager mWifiManager;

    private ConnectivityManager mConnectivityManager;

    private Context mContext;

    private PhoneInfo(Context context) {
        mContext = context;
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static PhoneInfo getInstance(Context context) {
        if (instance == null) {
            synchronized (PhoneInfo.class) {
                if (instance == null) {
                    instance = new PhoneInfo(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    public String getCurrentIP() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        return WifiUtil.convertIntIpAddress(wifiInfo.getIpAddress());
    }

    public byte[] getCurrentIPBytes() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        return WifiUtil.convertIntIpToBytes(wifiInfo.getIpAddress());

    }

    public String getMultiIP() {
        // 192.168.1.100/24
        String UDP_CLIENT_IP = getCurrentIP();
        if (UDP_CLIENT_IP != null) {
            String[] ipArray = UDP_CLIENT_IP.trim().split("\\.");
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 3; i++) {
                builder.append(ipArray[i]);
                builder.append(".");
            }
            builder.append("255");
            return builder.toString();
        }
        return null;
    }

    /**
     * 判断wifi是否连接
     */
    public boolean checkWifiConnected() {
        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected();
    }
}
